﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Entity.SqlServer;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using TomNet.IMSC.Core.Contracts.Common;
using TomNet.IMSC.Core.Contracts.Finance;
using TomNet.IMSC.Core.Contracts.Identity;
using TomNet.IMSC.Core.Contracts.Organization;
using TomNet.IMSC.Model.DbModels.Finance;
using TomNet.IMSC.Web.Areas.Finance.Controllers;
using TomNet.IMSC.Web.Areas.Finance.Models;
using TomNet.IMSC.Web.Common;
using TomNet.IMSC.Web.Filters;
using TomNet.IMSC.Web.Models.ApiParams;
using TomNet.IMSC.Web.Models.StaffApiParams;
using TomNet.Web.Mvc.UI;
using TomNet.Web.WebApi;

namespace TomNet.IMSC.Web.Controllers.StaffAPI
{
    [Description("API-金融")]
    [ApiAuthentication]
    public class StaffFinanceController : BaseApiController
    {

        public IFinanceBusinessLoanRunningsContract BusiLoanContract { get; set; }// 商贷
        public IFinancePublicAccumulationFundsRunningsContract PAContract { get; set; }// 公积金
        public IFinanceTransferRunningsContract TransferContract { set; get; }// 二手房过户
        public IFinanceRunningsContract Contract { get; set; }
        public IFinanceItemsContract ItemContract { set; get; }//金融项

        public IImagesContract ImagesContract { get; set; }//图片

        public IStaffContract StaffContract { get; set; }//业务销售人员
        public IMessageBoardsContract MessageBoardsContract { get; set; }//报备跟踪信息


        //权限 相关属性
        public IStaffRolesContract StaffRolesContract { get; set; }
        public IRoleAuthorityContract RoleAuthorityContract { get; set; }
        public IStaffAuthorityContract StaffAuthorityContract { get; set; }


        #region ======================金融报备列表 及上传图片


        [Description("StaffAPI-金融商贷-流水")]
        public IHttpActionResult FinanceRunningList()//[FromBody]StaffPageSearch entity
        {
            //if (entity == null)
            //{
            //    return Token(new AjaxResult("参数错误", AjaxResultType.Error), "");
            //}
            int[] states = new int[] { 1, 2 };
            var query = (from m in Contract.Entities//.AsEnumerable()
                         join sf in StaffContract.Entities on m.TransactStaffID equals sf.Id into staff
                         from sf1 in staff.DefaultIfEmpty()
                         where m.FilingState == 1// m.FinanceItemsID == (int)LoanType.商业贷款 //&& m.FilingTime >= beginDate && m.FilingTime < endDate
                         select new StaffFinanceRunningViewModel
                         {
                             Id = m.Id,
                             IntermediaryName = m.IntermediaryName,
                             UserName = m.UserName,
                             UserPhone = m.UserPhone,
                             CustomerName = m.CustomerName == null ? "" : m.CustomerName,
                             CustomerPhone = m.CustomerPhone == null ? "" : m.CustomerPhone,

                             FinanceItemsID = m.FinanceItemsID,
                             HouseOwnerName = m.HouseOwnerName,
                             HouseOwnerPhone = m.HouseOwnerPhone,
                             FilingTime = m.FilingTime,// m.FilingTime.ToString("yy-MM-dd HH:mm:ss"),// SqlFunctions.StringConvert DateName("yy", m.FilingTime),// 
                             TransactStaffName = m.TransactStaffID == 0 ? "" : sf1.Name,
                             TransactStaffPhone = m.TransactStaffID == 0 ? "" : sf1.Phone,

                             FilingState = m.FilingState,
                             State = m.State,
                             StateName = m.FilingState == 1 ? "报备待审核" : "报备已审核",
                             Progress = m.Progress,
                             Remark = m.FilingAuditingRemark,

                         });



            //数据总数
            var total = query.Count();

            //默认给一个排序的字段
            query = query.OrderByDescending(m => m.FilingTime);


            List<StaffFinanceRunningViewModel> _list = query.ToList();

            foreach (StaffFinanceRunningViewModel item in _list)
            {
                //item.StateName = GetBusinessProgressState(Contract.GetByKey(item.Id), BusiLoanContract.Entities.Where(x => x.FinanceRunningsID == item.Id).FirstOrDefault()).Name;
                item.FilingTimeStr = item.FilingTime.ToString("yy-MM-dd HH:mm");
            }

            Func<int, string> func = abc =>
            {
                string financeType = "";
                if ((LoanType)abc == LoanType.商业贷款)
                {
                    financeType = LoanType.商业贷款.ToString();
                }
                else
                {
                    int def = ItemContract.GetByKey(abc).ParentID;
                    switch ((LoanType)def)
                    {
                        case LoanType.公积金贷款:
                            financeType = LoanType.公积金贷款.ToString();
                            break;
                        case LoanType.金融过户:
                            financeType = LoanType.金融过户.ToString();
                            break;
                        default:
                            break;
                    }
                }
                return financeType;
            };

            var result = new AjaxResult("成功", AjaxResultType.Success, _list.Select(x => new
            {
                x.Id,
                x.IntermediaryName,
                x.UserName,
                x.UserPhone,
                x.CustomerName,
                x.CustomerPhone,
                x.HouseOwnerName,
                x.HouseOwnerPhone,
                x.FilingTimeStr,
                x.Remark,
                x.FilingState,
                x.StateName,
                FinanceType = func(x.FinanceItemsID),

            }));
            return Token(result, "");

        }



        #endregion


        private List<string> getImages(int financeRunningId, int type)
        {
            return ImagesContract.Entities.Where(x => x.GroupID == 9 && x.InterfixID == financeRunningId && x.ImageType == type)
                                   .Select(x => new BaseName { Name = x.ImagePath + x.FileName }).Select(x => x.Name)
                                   .ToList();
        }
        private List<StaffFinanceRunningViewModel> GetBusinessRunningList(StaffPageSearch entity, List<int> staffAuth, int staffId)
        {
            var query = (from m in Contract.Entities
                         join sf in StaffContract.Entities on m.TransactStaffID equals sf.Id into staff
                         from sf1 in staff.DefaultIfEmpty()
                         where m.FinanceItemsID == (int)LoanType.商业贷款
                         select new StaffFinanceRunningViewModel
                         {
                             Id = m.Id,
                             IntermediaryName = m.IntermediaryName,
                             UserName = m.UserName,
                             UserPhone = m.UserPhone,
                             CustomerName = m.CustomerName == null ? "" : m.CustomerName,
                             CustomerPhone = m.CustomerPhone == null ? "" : m.CustomerPhone,

                             FinanceItemsID = m.FinanceItemsID,
                             HouseOwnerName = m.HouseOwnerName,
                             HouseOwnerPhone = m.HouseOwnerPhone,
                             FilingTime = m.FilingTime,

                             SellStaffID = m.SellStaffID,
                             TransactStaffID = m.TransactStaffID,
                             TransactStaffName = m.TransactStaffID == 0 ? "" : sf1.Name,
                             TransactStaffPhone = m.TransactStaffID == 0 ? "" : sf1.Phone,

                             FilingState = m.FilingState,
                             State = m.State,
                             Progress = m.Progress,
                             Remark = m.Remark,

                         });

            //条件搜索
            if (!staffAuth.Contains(294))//查看所有交易记录
            {
                query = query.Where(x => x.SellStaffID == staffId || x.TransactStaffID == staffId);
            }

            if (!string.IsNullOrWhiteSpace(entity.KeyWord))//中介名称//经纪人名//
            {
                query = query.Where(m => m.CustomerName.Contains(entity.KeyWord) || m.CustomerPhone.Contains(entity.KeyWord) || m.IntermediaryName.Contains(entity.KeyWord)
                || m.UserName.Contains(entity.KeyWord) || m.UserPhone.Contains(entity.KeyWord) || m.TransactStaffName.Contains(entity.KeyWord));
            }
            if (entity.BeginTime != null && entity.EndTime != null)
            {
                entity.EndTime = entity.EndTime.AddDays(1);
                query = query.Where(x => x.FilingTime >= (entity.BeginTime) && x.FilingTime < (entity.EndTime));
            }
            if (entity.State != 0)
            {
                query = query.Where(x => x.Progress == entity.State);
            }

            //数据总数
            var total = query.Count();

            //默认给一个排序的字段
            query = query.OrderByDescending(m => m.FilingTime);

            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((entity.PageIndex - 1) * entity.PageSize).Take(entity.PageSize)
                : Enumerable.Empty<StaffFinanceRunningViewModel>().AsQueryable();// null;


            return query.ToList();
        }
        private List<StaffFinanceRunningViewModel> GetTransferRunningList(StaffPageSearch entity, List<int> staffAuth, int staffId)
        {
            int[] _arr = ItemContract.Entities.Where(x => x.ParentID == (int)LoanType.金融过户).Select(x => x.Id).ToArray();
            var query = (from m in Contract.Entities
                         join sf in StaffContract.Entities on m.TransactStaffID equals sf.Id into staff
                         from sf1 in staff.DefaultIfEmpty()
                         where _arr.Contains(m.FinanceItemsID)
                         select new StaffFinanceRunningViewModel
                         {
                             Id = m.Id,
                             IntermediaryName = m.IntermediaryName,
                             UserName = m.UserName,
                             UserPhone = m.UserPhone,
                             CustomerName = m.CustomerName == null ? "" : m.CustomerName,
                             CustomerPhone = m.CustomerPhone == null ? "" : m.CustomerPhone,

                             FinanceItemsID = m.FinanceItemsID,
                             HouseOwnerName = m.HouseOwnerName,
                             HouseOwnerPhone = m.HouseOwnerPhone,
                             FilingTime = m.FilingTime,

                             SellStaffID = m.SellStaffID,
                             TransactStaffID =m.TransactStaffID,
                             TransactStaffName = m.TransactStaffID == 0 ? "" : sf1.Name,
                             TransactStaffPhone = m.TransactStaffID == 0 ? "" : sf1.Phone,

                             FilingState = m.FilingState,
                             State = m.State,
                             Progress = m.Progress,
                             Remark = m.Remark,

                         });

            //条件搜索
            if (!staffAuth.Contains(294))//查看所有交易记录
            {
                query = query.Where(x => x.SellStaffID == staffId || x.TransactStaffID == staffId);
            }

            if (!string.IsNullOrWhiteSpace(entity.KeyWord))//中介名称//经纪人名//
            {
                query = query.Where(m => m.CustomerName.Contains(entity.KeyWord) || m.CustomerPhone.Contains(entity.KeyWord) || m.IntermediaryName.Contains(entity.KeyWord)
                || m.UserName.Contains(entity.KeyWord) || m.UserPhone.Contains(entity.KeyWord) || m.TransactStaffName.Contains(entity.KeyWord));
            }
            if (entity.BeginTime != null && entity.EndTime != null)
            {
                entity.EndTime = entity.EndTime.AddDays(1);
                query = query.Where(x => x.FilingTime >= (entity.BeginTime) && x.FilingTime < (entity.EndTime));
            }
            if (entity.State != 0)
            {
                query = query.Where(x => x.Progress == entity.State);
            }

            //数据总数
            var total = query.Count();

            //默认给一个排序的字段
            query = query.OrderByDescending(m => m.FilingTime);

            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((entity.PageIndex - 1) * entity.PageSize).Take(entity.PageSize)
                : Enumerable.Empty<StaffFinanceRunningViewModel>().AsQueryable();// null;


            //List<StaffFinanceRunningViewModel> _list = query.ToList();
            return query.ToList();
        }
        private List<StaffFinanceRunningViewModel> GetFundRunningList(StaffPageSearch entity, List<int> staffAuth, int staffId)
        {
            int[] _arr = ItemContract.Entities.Where(x => x.ParentID == (int)LoanType.公积金贷款).Select(x => x.Id).ToArray();
            var query = (from m in Contract.Entities//.AsEnumerable()
                         join sf in StaffContract.Entities on m.TransactStaffID equals sf.Id into staff
                         from sf1 in staff.DefaultIfEmpty()
                         where _arr.Contains(m.FinanceItemsID)// && m.FilingTime >= entity.BeginTime && m.FilingTime < entity.EndTime
                         select new StaffFinanceRunningViewModel
                         {
                             Id = m.Id,
                             IntermediaryName = m.IntermediaryName,
                             UserName = m.UserName,
                             UserPhone = m.UserPhone,
                             CustomerName = m.CustomerName == null ? "" : m.CustomerName,
                             CustomerPhone = m.CustomerPhone == null ? "" : m.CustomerPhone,

                             FinanceItemsID = m.FinanceItemsID,
                             HouseOwnerName = m.HouseOwnerName,
                             HouseOwnerPhone = m.HouseOwnerPhone,
                             FilingTime = m.FilingTime,// m.FilingTime.ToString("yy-MM-dd HH:mm:ss"),// SqlFunctions.StringConvert DateName("yy", m.FilingTime),// 

                             SellStaffID = m.SellStaffID,
                             TransactStaffID = m.TransactStaffID,
                             TransactStaffName = m.TransactStaffID == 0 ? "" : sf1.Name,
                             TransactStaffPhone = m.TransactStaffID == 0 ? "" : sf1.Phone,

                             FilingState = m.FilingState,
                             State = m.State,
                             Progress = m.Progress,
                             Remark = m.Remark == null ? "" : m.Remark,

                         });

            //条件搜索
            if (!staffAuth.Contains(294))//查看所有交易记录
            {
                query = query.Where(x => x.SellStaffID == staffId || x.TransactStaffID == staffId);
            }

            if (!string.IsNullOrWhiteSpace(entity.KeyWord))//中介名称//经纪人名//
            {
                query = query.Where(m => m.CustomerName.Contains(entity.KeyWord) || m.CustomerPhone.Contains(entity.KeyWord) || m.IntermediaryName.Contains(entity.KeyWord)
                || m.UserName.Contains(entity.KeyWord) || m.UserPhone.Contains(entity.KeyWord) || m.TransactStaffName.Contains(entity.KeyWord));
            }
            if (entity.BeginTime != null && entity.EndTime != null)
            {
                entity.EndTime = entity.EndTime.AddDays(1);
                query = query.Where(x => x.FilingTime >= (entity.BeginTime) && x.FilingTime < (entity.EndTime));
            }
            if (entity.State != 0)
            {
                query = query.Where(x => x.Progress == entity.State);
            }

            //数据总数
            var total = query.Count();

            //默认给一个排序的字段
            query = query.OrderByDescending(m => m.FilingTime);

            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((entity.PageIndex - 1) * entity.PageSize).Take(entity.PageSize)
                : Enumerable.Empty<StaffFinanceRunningViewModel>().AsQueryable();// null;


            //List<StaffFinanceRunningViewModel> _list = query.ToList();
            return query.ToList(); ;
        }



        #region ======================金融报备历史记录 及上传图片

        private List<int> getStaffRoleAuth(int staffId)
        {
            List<int> al = new List<int>();
            var qa = from a in RoleAuthorityContract.Entities
                     join
                         b in StaffRolesContract.Entities on a.RoleID equals b.RoleID
                     where b.StaffID == staffId
                     select a.AuthorityID;
            al.AddRange(qa.ToList());
            var sa = from a in StaffAuthorityContract.Entities
                     where a.StaffID == staffId
                     select a.AuthorityID;
            al.AddRange(sa.ToList());
            //staffId = staff.Id;
            return al;
        }

        [Description("StaffAPI-商贷历史记录-流水")]
        public IHttpActionResult BusinessRunningListHistory([FromBody]StaffPageSearch entity)
        {
            if (entity == null)
            {
                return Token(new AjaxResult("参数错误", AjaxResultType.Error), "");
            }


            Model.DbModels.Organization.Staff staff = StaffContract.GetByKey(BaseWebApiExt.GetStaffIDByToken());
            List<StaffFinanceRunningViewModel> _list = GetBusinessRunningList(entity, getStaffRoleAuth(staff.Id), staff.Id);
            foreach (StaffFinanceRunningViewModel item in _list)
            {
                item.StateName = GetBusinessProgressState(Contract.GetByKey(item.Id), BusiLoanContract.Entities.Where(x => x.FinanceRunningsID == item.Id).FirstOrDefault()).Name;
                item.FilingTimeStr = item.FilingTime.ToString("yy-MM-dd HH:mm");

                item.Contract = getImages(item.Id, 1);

                item.Approve = getImages(item.Id, 2);

                item.Provide = getImages(item.Id, 3);

            }


            var result = new AjaxResult("成功", AjaxResultType.Success, _list.Select(x => new
            {
                x.Id,
                x.IntermediaryName,
                x.UserName,
                x.UserPhone,
                x.CustomerName,
                x.CustomerPhone,
                x.HouseOwnerName,
                x.HouseOwnerPhone,
                x.FilingTimeStr,
                x.Remark,
                x.FilingState,
                x.StateName,
                x.Contract,
                x.Approve,
                x.Provide,

                x.Progress,
                FinanceType = (int)LoanType.商业贷款,
                ImageType = 1 //上传图片标识（面签）
            }));
            return Token(result, "");
        }

        [Description("StaffAPI-公积金历史记录-流水")]
        public IHttpActionResult FundRunningListHistory([FromBody]StaffPageSearch entity)
        {
            if (entity == null)
            {
                return Token(new AjaxResult("参数错误", AjaxResultType.Error), "");
            }
            Model.DbModels.Organization.Staff staff = StaffContract.GetByKey(BaseWebApiExt.GetStaffIDByToken());
            List<StaffFinanceRunningViewModel> _list = GetFundRunningList(entity, getStaffRoleAuth(staff.Id), staff.Id);
            foreach (StaffFinanceRunningViewModel item in _list)
            {
                item.StateName = GetFundsProgressState(Contract.GetByKey(item.Id), PAContract.Entities.Where(x => x.FinanceRunningsID == item.Id).FirstOrDefault()).Name;
                item.FilingTimeStr = item.FilingTime.ToString("yy-MM-dd HH:mm");

                item.Contract = getImages(item.Id, 1);
                //ImagesContract.Entities.Where(x => x.GroupID == 9 && x.InterfixID == item.Id && x.ImageType == 1)
                // .Select(x => new BaseName { Name = x.ImagePath + x.FileName }).Select(x => x.Name)
                // .ToList();
                item.Approve = getImages(item.Id, 2);
                //ImagesContract.Entities.Where(x => x.GroupID == 9 && x.InterfixID == item.Id && x.ImageType == 2)
                //   .Select(x => new BaseName { Name = x.ImagePath + x.FileName }).Select(x => x.Name)
                //   .ToList();
                item.Provide = getImages(item.Id, 3);
                //ImagesContract.Entities.Where(x => x.GroupID == 9 && x.InterfixID == item.Id && x.ImageType == 3)
                //    .Select(x => new BaseName { Name = x.ImagePath + x.FileName }).Select(x => x.Name)
                //    .ToList();
            }


            var result = new AjaxResult("成功", AjaxResultType.Success, _list.Select(x => new
            {
                x.Id,
                x.IntermediaryName,
                x.UserName,
                x.UserPhone,
                x.CustomerName,
                x.CustomerPhone,
                x.HouseOwnerName,
                x.HouseOwnerPhone,
                x.FilingTimeStr,
                x.Remark,
                x.FilingState,
                x.StateName,
                x.Contract,
                x.Approve,
                x.Provide,

                x.Progress,
                FinanceType = (int)LoanType.公积金贷款,
                ImageType = 2 //上传图片标识（审批）
            }));

            return Token(result, "");
        }


        [Description("StaffAPI-金融过户历史记录-流水")]
        public IHttpActionResult TransferRunningListHistory([FromBody]StaffPageSearch entity)
        {
            if (entity == null)
            {
                return Token(new AjaxResult("参数错误", AjaxResultType.Error), "");
            }
            Model.DbModels.Organization.Staff staff = StaffContract.GetByKey(BaseWebApiExt.GetStaffIDByToken());
            List<StaffFinanceRunningViewModel> _list = GetTransferRunningList(entity, getStaffRoleAuth(staff.Id), staff.Id);

            foreach (StaffFinanceRunningViewModel item in _list)
            {
                item.StateName = GetTransferProgressState(Contract.GetByKey(item.Id), TransferContract.Entities.Where(x => x.FinanceRunningsID == item.Id).FirstOrDefault()).Name;
                item.FilingTimeStr = item.FilingTime.ToString("yy-MM-dd HH:mm");

                ////上传面签 审核 放款图片
                item.Contract = getImages(item.Id, 1);
                //ImagesContract.Entities.Where(x => x.GroupID == 9 && x.InterfixID == item.Id && x.ImageType == 1)
                //                 .Select(x => new BaseName { Name = x.ImagePath + x.FileName }).Select(x => x.Name)
                //                 .ToList();
                item.Approve = getImages(item.Id, 2);
                //ImagesContract.Entities.Where(x => x.GroupID == 9 && x.InterfixID == item.Id && x.ImageType == 2)
                //   .Select(x => new BaseName { Name = x.ImagePath + x.FileName }).Select(x => x.Name)
                //   .ToList();
                item.Provide = getImages(item.Id, 3);
                //ImagesContract.Entities.Where(x => x.GroupID == 9 && x.InterfixID == item.Id && x.ImageType == 3)
                //    .Select(x => new BaseName { Name = x.ImagePath + x.FileName }).Select(x => x.Name)
                //    .ToList();
            }


            var result = new AjaxResult("成功", AjaxResultType.Success, _list.Select(x => new
            {
                x.Id,
                x.IntermediaryName,
                x.UserName,
                x.UserPhone,
                x.CustomerName,
                x.CustomerPhone,
                x.HouseOwnerName,
                x.HouseOwnerPhone,
                x.FilingTimeStr,
                x.Remark,
                x.FilingState,
                x.StateName,
                x.Contract,
                x.Approve,
                x.Provide,

                x.Progress,
                FinanceType = (int)LoanType.金融过户,
                ImageType = 3 //上传图片标识（放款）
            }));
            return Token(result, "");
        }
        #endregion



        #region 手机助手 后台处理金融报备


        [Description("StaffAPI-金融报备审核")]
        public IHttpActionResult FinanceFilingAuditing([FromBody]FinanceViewModel entity)
        {
            if (entity == null)
            {
                return Token(new AjaxResult("参数错误", AjaxResultType.Error), "");
            }
            try
            {
                string returnText = "";
                Contract.Repository.UnitOfWork.BeginTransaction();
                //获取UserID
                int userId = BaseWebApiExt.GetStaffIDByToken(); // GetUserIDByToken();

                FinanceRunnings item = Contract.GetByKey(entity.Id);
                switch (item.Progress)
                {
                    case 1:

                        if (entity.DoOption == 1)
                        {
                            item.FilingState = 2;
                            item.FilingAuditingTime = DateTime.Now;
                            item.FilingAuditingStaffID = userId;
                            item.FilingAuditingRemark = entity.Remark;

                            item.CollectDataState = 1;
                            item.Progress = 2;
                        }
                        else
                        {
                            item.FilingState = 3;
                            item.FilingAuditingTime = DateTime.Now;
                            item.FilingAuditingStaffID = userId;
                            item.FilingAuditingRemark = entity.Remark;

                            item.CollectDataState = 0;
                            item.Progress = 1;
                        }

                        break;
                    default:
                        switch ((LoanType)Enum.ToObject(typeof(LoanType), entity.FinanceType))
                        {
                            case LoanType.商业贷款:
                                item = UpdateFinanceBusiness(entity, item, userId, out returnText);
                                break;
                            case LoanType.公积金贷款:
                                item = UpdateFinanceFund(entity, item, userId, out returnText);
                                break;
                            case LoanType.金融过户:
                                item = UpdateFinanceTransfer(entity, item, userId, out returnText);
                                break;
                        }
                        break;
                }
                Contract.Update(item);
                Contract.Repository.UnitOfWork.Commit();

                var result = new AjaxResult();// string.IsNullOrEmpty(returnText) ? "成功" : returnText, AjaxResultType.Success);
                if (string.IsNullOrEmpty(returnText) || returnText == "成功")
                {
                    result.Content = "成功";
                    result.Type = AjaxResultType.Success;
                }
                else
                {
                    result.Content = returnText;
                    result.Type = AjaxResultType.Error;
                }
                return Token(result, "");
            }
            catch (Exception ex)
            {
                Contract.Repository.UnitOfWork.Rollback();
                return Token(new AjaxResult("操作失败", AjaxResultType.Error), "");
            }
        }


        private FinanceRunnings UpdateFinanceBusiness(FinanceViewModel entity, FinanceRunnings item, int userId, out string text)
        {
            FinanceBusinessLoanRunnings business = BusiLoanContract.Entities.First(x => x.FinanceRunningsID == entity.Id);

            if (business != null)
            {
                BaseRemark _progress = GetBusinessProgressState(item, business);
                switch (_progress.Id)
                {
                    case 3://设置面签时间 和备注

                        business.ContractRemark = entity.Remark;
                        business.ContractStaffID = userId;
                        business.ContractState = 1;
                        business.ContractTime = entity.DoTime;

                        item.Progress = 3;

                        BusiLoanContract.Update(business);
                        text = "成功";
                        break;
                    case 4://对面签的操作-并检测是否已经上传图片
                        if (getImages(item.Id, 1).Count <= 0)
                        {
                            text = "缺少资料图片";
                            break;
                        }
                        if (entity.DoOption == 1)//同意
                        {
                            business.ContractState = 2;

                            business.ApproveRemark = entity.Remark;
                            business.ApproveStaffID = userId;
                            business.ApproveState = 1;
                            business.ApproveTime = entity.DoTime;

                            //business.ProvideState = 1;
                            item.Progress = 4;
                        }
                        else if (entity.DoOption == 2)
                        {
                            business.ApproveRemark = entity.Remark;
                            business.ApproveStaffID = userId;
                            business.ApproveState = 3;
                            business.ApproveTime = DateTime.Now;

                            item.Progress = 3;
                        }
                        text = "成功";
                        BusiLoanContract.Update(business);
                        break;
                    case 5://对审批的操作-并检测是否已经上传图片
                        if (getImages(item.Id, 2).Count <= 0)
                        {
                            text = "缺少资料图片";
                            break;
                        }
                        if (entity.DoOption == 1)//同意
                        {
                            business.ApproveState = 2;

                            business.ProvideRemark = entity.Remark;
                            business.ProvideStaffID = userId;
                            business.ProvideState = 1;
                            business.ProvideTime = entity.DoTime;

                            item.Progress = 5;
                        }
                        else if (entity.DoOption == 2)
                        {
                            business.ProvideRemark = entity.Remark;
                            business.ProvideStaffID = userId;
                            business.ProvideState = 3;
                            business.ProvideTime = DateTime.Now;

                            item.Progress = 4;
                        }
                        text = "成功";
                        BusiLoanContract.Update(business);
                        break;
                    case 6://确认放款-上传图片
                        if (getImages(item.Id, 3).Count <= 0)
                        {
                            text = "缺少资料图片";
                            break;
                        }

                        if (entity.DoOption == 1)//同意
                        {
                            business.ApproveState = 2;

                            business.ProvideRemark = entity.Remark;
                            business.ProvideStaffID = userId;
                            business.ProvideState = 1;
                            business.ProvideTime = entity.DoTime;

                            item.Progress = 5;
                        }
                        else if (entity.DoOption == 2)
                        {
                            business.ProvideRemark = entity.Remark;
                            business.ProvideStaffID = userId;
                            business.ProvideState = 3;
                            business.ProvideTime = DateTime.Now;

                            item.Progress = 5;
                        }
                        text = "成功";
                        BusiLoanContract.Update(business);
                        break;
                    default:
                        text = "操作失败";
                        break;
                }
            }
            else
                text = "操作失败";
            return item;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="item"></param>
        /// <param name="userId"></param>
        /// <param name="text"></param>
        /// <returns></returns>
        private FinanceRunnings UpdateFinanceFund(FinanceViewModel entity, FinanceRunnings item, int userId, out string text)
        {

            FinancePublicAccumulationFundsRunnings business = PAContract.Entities.First(x => x.FinanceRunningsID == entity.Id);
            if (business != null)
            {
                BaseRemark _progress = GetFundsProgressState(item, business);
                switch (_progress.Id)
                {
                    case 3:
                        business.ContractRemark = entity.Remark;
                        business.ContractStaffID = userId;
                        business.ContractState = 1;
                        business.ContractTime = entity.DoTime;

                        text = "成功";
                        PAContract.Update(business);
                        break;
                    case 4:
                        if (getImages(item.Id, 1).Count <= 0)
                        {
                            text = "缺少资料图片";
                            break;
                        }
                        if (entity.DoOption == 1)//同意
                        {
                            business.ContractState = 2;

                            business.MortgageRemark = entity.Remark;
                            business.MortgageStaffID = userId;
                            business.MortgageState = 1;
                            business.MortgageTime = entity.DoTime;

                            //business.ProvideState = 1;
                            item.Progress = 4;
                        }
                        else if (entity.DoOption == 2)
                        {
                            business.MortgageRemark = entity.Remark;
                            business.MortgageStaffID = userId;
                            business.MortgageState = 3;
                            business.MortgageTime = DateTime.Now;

                            item.Progress = 3;
                        }
                        text = "成功"; PAContract.Update(business);
                        break;
                    case 5:
                        if (getImages(item.Id, 2).Count <= 0)
                        {
                            text = "缺少资料图片";
                            break;
                        }
                        if (entity.DoOption == 1)//同意
                        {
                            business.MortgageState = 2;

                            business.ProvideRemark = entity.Remark;
                            business.ProvideStaffID = userId;
                            business.ProvideState = 2;
                            business.ProvideTime = entity.DoTime;

                            item.Progress = 5;
                        }
                        else if (entity.DoOption == 2)
                        {
                            business.ProvideRemark = entity.Remark;
                            business.ProvideStaffID = userId;
                            business.ProvideState = 3;
                            business.ProvideTime = DateTime.Now;

                            item.Progress = 4;
                        }
                        text = "成功"; PAContract.Update(business);
                        break;
                    case 6:
                        if (getImages(item.Id, 3).Count <= 0)
                        {
                            text = "缺少资料图片";
                            break;
                        }
                        if (entity.DoOption == 1)//同意
                        {
                            business.MortgageState = 2;

                            business.ProvideRemark = entity.Remark;
                            business.ProvideStaffID = userId;
                            business.ProvideState = 2;
                            business.ProvideTime = entity.DoTime;

                            item.Progress = 5;
                        }
                        else if (entity.DoOption == 2)
                        {
                            business.ProvideRemark = entity.Remark;
                            business.ProvideStaffID = userId;
                            business.ProvideState = 3;
                            business.ProvideTime = DateTime.Now;

                            item.Progress = 4;
                        }
                        text = "成功";
                        PAContract.Update(business);
                        break;
                    default:
                        text = "操作失败";
                        break;
                }


            }
            else
                text = "操作失败";
            return item;
        }

        private FinanceRunnings UpdateFinanceTransfer(FinanceViewModel entity, FinanceRunnings item, int userId, out string text)
        {

            FinanceTransferRunnings business = TransferContract.Entities.First(x => x.FinanceRunningsID == entity.Id);
            if (business != null)
            {
                BaseRemark _progress = GetTransferProgressState(item, business);
                switch (_progress.Id)
                {
                    case 3:
                        //if (entity.DoOption == 1)//同意
                        //{
                        business.QueryArchivesRemark = entity.Remark;
                        business.QueryArchivesStaffID = userId;
                        business.QueryArchivesState = 1;
                        business.QueryArchivesTime = entity.DoTime;

                        //business.TransferState = 1;
                        item.Progress = 4;
                        //}
                        //else if (entity.DoOption == 2)
                        //{
                        //    business.QueryArchivesRemark = entity.Remark;
                        //    business.QueryArchivesStaffID = userId;
                        //    business.QueryArchivesState = 3;
                        //    business.QueryArchivesTime = DateTime.Now;

                        //    item.Progress = 3;
                        //}
                        text = "成功"; TransferContract.Update(business);
                        break;
                    case 4:
                        if (getImages(item.Id, 1).Count <= 0)
                        {
                            text = "缺少资料图片";
                            break;
                        }
                        if (entity.DoOption == 1)//同意
                        {
                            business.QueryArchivesState = 2;

                            business.TransferRemark = entity.Remark;
                            business.TransferStaffID = userId;
                            business.TransferState = 1;
                            business.TransferTime = entity.DoTime;

                            //business.CredentialsState = 1;
                            item.Progress = 5;
                        }
                        else if (entity.DoOption == 2)
                        {
                            business.TransferRemark = entity.Remark;
                            business.TransferStaffID = userId;
                            business.TransferState = 3;
                            business.TransferTime = DateTime.Now;

                            item.Progress = 4;
                        }
                        text = "成功"; TransferContract.Update(business);
                        break;
                    case 5:
                        if (getImages(item.Id, 2).Count <= 0)
                        {
                            text = "缺少资料图片";
                            break;
                        }
                        if (entity.DoOption == 1)//同意
                        {
                            business.TransferState = 2;

                            business.CredentialsRemark = entity.Remark;
                            business.CredentialsStaffID = userId;
                            business.CredentialsState = 1;
                            business.CredentialsTime = entity.DoTime;

                            item.Progress = 5;
                        }
                        else if (entity.DoOption == 2)
                        {
                            business.CredentialsRemark = entity.Remark;
                            business.CredentialsStaffID = userId;
                            business.CredentialsState = 3;
                            business.CredentialsTime = DateTime.Now;

                            item.Progress = 5;
                        }
                        text = "成功"; TransferContract.Update(business);
                        break;
                    case 6:
                        if (getImages(item.Id, 3).Count <= 0)
                        {
                            text = "缺少资料图片";
                            break;
                        }
                        if (entity.DoOption == 1)//同意
                        {
                            business.TransferState = 2;

                            business.CredentialsRemark = entity.Remark;
                            business.CredentialsStaffID = userId;
                            business.CredentialsState = 1;
                            business.CredentialsTime = entity.DoTime;

                            item.Progress = 5;
                        }
                        else if (entity.DoOption == 2)
                        {
                            business.CredentialsRemark = entity.Remark;
                            business.CredentialsStaffID = userId;
                            business.CredentialsState = 3;
                            business.CredentialsTime = DateTime.Now;

                            item.Progress = 5;
                        }
                        text = "成功"; TransferContract.Update(business);
                        break;
                    default:
                        text = "操作失败";
                        break;

                }

            }
            else
                text = "操作失败";
            return item;
        }

        #endregion




        private BaseRemark GetBusinessProgressState(FinanceRunnings entity, FinanceBusinessLoanRunnings loanEntity)
        {
            //拒绝时，显示当前操作时间
            BaseRemark stepIdx = new BaseRemark();

            if (entity.FilingState == 1)//报备待审核
            {
                stepIdx = new BaseRemark() { Id = 0, Name = "报备待审核", Value = entity.FilingTime };//0;
            }
            else if (entity.FilingState == 3)//拒绝时，显示当前操作时间
            {
                stepIdx = new BaseRemark() { Id = 0, Name = "报备审核" + Progress_State.已终止, Value = entity.FilingAuditingTime, Remark = entity.FilingAuditingRemark };//0;
            }
            else if (entity.FilingState == 2)
            {//报备审核已完成
             //stepIdx = new BaseName() { Id = 0, Name = "报备待审核" };//1;
                if (entity.CollectDataState == 1)//搜集资料待完成
                {
                    stepIdx = new BaseRemark() { Id = 1, Name = "备件" + Progress_State.进行中, Value = entity.FilingAuditingTime, Remark = entity.FilingAuditingRemark };//1;
                }
                else if (entity.CollectDataState == 3)//资料不全，被终止
                {
                    stepIdx = new BaseRemark() { Id = 1, Name = "备件" + Progress_State.已终止, Value = entity.CollectDataTime, Remark = entity.CollectDataRemark };//0;
                }
                else if (entity.CollectDataState == 2)////搜集资料已完成
                {
                    //stepIdx = new BaseRemark() { Id = 2, Name = "资料搜集 已完成", Value = frViewModel.FilingAuditingTime, Remark= entity.CollectDataRemark };//2;
                    if (loanEntity.ContractState == 0)//分配办件人
                    {
                        stepIdx = new BaseRemark() { Id = 2, Name = "备件" + Progress_State.已完成, Remark = entity.CollectDataRemark };//2;
                        if (entity.TransactStaffID != 0)
                        {
                            stepIdx = new BaseRemark() { Id = 3, Name = "面签准备中", Remark = loanEntity.ContractRemark };//3;
                        }
                    }
                    else if (loanEntity.ContractState == 1)
                    {
                        stepIdx = new BaseRemark() { Id = 4, Name = "面签" + Progress_State.进行中, Value = loanEntity.ContractTime, Remark = loanEntity.ContractRemark };//4;
                    }
                    else if (loanEntity.ContractState == 3)
                    {
                        stepIdx = new BaseRemark() { Id = 4, Name = "面签" + Progress_State.已终止, Value = loanEntity.ContractTime, Remark = loanEntity.ContractRemark };//4;
                    }
                    else if (loanEntity.ContractState == 2)
                    {
                        //stepIdx = new BaseRemark() { Id = 5, Name = "面签 已完成", Value = loanEntity.ContractTime, Remark = loanEntity.ApproveRemark };//5;
                        if (loanEntity.ApproveState == 1)//审批进行中
                        {
                            stepIdx = new BaseRemark() { Id = 5, Name = "面签" + Progress_State.已完成, Value = loanEntity.ContractTime, Remark = loanEntity.ProvideRemark };//5;
                        }
                        else if (loanEntity.ApproveState == 3)
                        {
                            stepIdx = new BaseRemark() { Id = 5, Name = "审批" + Progress_State.已终止, Value = loanEntity.ApproveTime, Remark = loanEntity.ProvideRemark };//5;
                        }
                        else if (loanEntity.ApproveState == 2)
                        {
                            //stepIdx = new BaseRemark() { Id = 6, Name = "审批 已完成", Value = loanEntity.ApproveTime, Remark = loanEntity.ProvideRemark };//6;
                            if (loanEntity.ProvideState == 1)
                            {
                                stepIdx = new BaseRemark() { Id = 6, Name = "放款" + Progress_State.进行中, Value = loanEntity.ProvideTime, Remark = loanEntity.ProvideRemark };//6;
                            }
                            else if (loanEntity.ProvideState == 2)
                            {
                                stepIdx = new BaseRemark() { Id = 7, Name = "放款" + Progress_State.已完成, Value = loanEntity.ProvideTime, Remark = loanEntity.ProvideRemark };// 7;
                            }
                            else if (loanEntity.ProvideState == 3)
                            {
                                stepIdx = new BaseRemark() { Id = 7, Name = "放款" + Progress_State.已终止, Value = loanEntity.ProvideTime, Remark = loanEntity.ProvideRemark };//7;
                            }
                        }
                    }
                }
            }

            return stepIdx;

        }

        private BaseRemark GetFundsProgressState(FinanceRunnings entity, FinancePublicAccumulationFundsRunnings loanEntity)
        {

            BaseRemark stepIdx = new BaseRemark();//  0;


            if (entity.FilingState == 1)//报备待审核
            {
                stepIdx = new BaseRemark() { Id = 0, Name = "报备待审核", Value = entity.FilingTime };//0;
            }
            else if (entity.FilingState == 3)//拒绝时，显示当前操作时间
            {
                stepIdx = new BaseRemark() { Id = 0, Name = "报备审核" + Progress_State.已终止, Value = entity.FilingAuditingTime, Remark = entity.FilingAuditingRemark };//0;
            }
            else if (entity.FilingState == 2)
            {//报备审核已完成
             //stepIdx = 1;
                if (entity.CollectDataState == 1)//搜集资料待完成
                {
                    stepIdx = new BaseRemark() { Id = 1, Name = "备件" + Progress_State.进行中, Value = entity.FilingAuditingTime, Remark = entity.FilingAuditingRemark };//1;
                }
                else if (entity.CollectDataState == 3)//资料不全，被终止
                {
                    stepIdx = new BaseRemark() { Id = 1, Name = "备件" + Progress_State.已终止, Value = entity.CollectDataTime, Remark = entity.CollectDataRemark };//0;
                }
                else if (entity.CollectDataState == 2)////搜集资料已完成
                {
                    //stepIdx = 2;
                    if (loanEntity.ContractState == 0)//分配办件人
                    {
                        stepIdx = new BaseRemark() { Id = 2, Name = "备件" + Progress_State.已完成, Remark = entity.CollectDataRemark };//2;
                        if (entity.TransactStaffID != 0)
                        {
                            stepIdx = new BaseRemark() { Id = 3, Name = "面签准备中", Remark = loanEntity.ContractRemark };//3;
                        }
                    }
                    else if (loanEntity.ContractState == 1)
                    {
                        stepIdx = new BaseRemark() { Id = 4, Name = "面签" + Progress_State.进行中, Value = loanEntity.ContractTime, Remark = loanEntity.ContractRemark };//4;
                    }
                    else if (loanEntity.ContractState == 3)
                    {
                        stepIdx = new BaseRemark() { Id = 4, Name = "面签" + Progress_State.已终止, Value = loanEntity.ContractTime, Remark = loanEntity.ContractRemark };//4;
                    }
                    else if (loanEntity.ContractState == 2)
                    {
                        //stepIdx = 5;
                        if (loanEntity.MortgageState == 1)//审批进行中
                        {
                            stepIdx = new BaseRemark() { Id = 5, Name = "面签" + Progress_State.已完成, Value = loanEntity.ContractTime, Remark = loanEntity.MortgageRemark };//5;
                        }
                        else if (loanEntity.MortgageState == 3)
                        {
                            stepIdx = new BaseRemark() { Id = 5, Name = "审批" + Progress_State.已终止, Value = loanEntity.MortgageTime, Remark = loanEntity.MortgageRemark };//5;
                        }
                        else if (loanEntity.MortgageState == 2)
                        {
                            //stepIdx = 6;
                            if (loanEntity.ProvideState == 1)
                            {
                                stepIdx = new BaseRemark() { Id = 6, Name = "放款" + Progress_State.进行中, Value = loanEntity.ProvideTime, Remark = loanEntity.ProvideRemark };//6;
                            }
                            else if (loanEntity.ProvideState == 2)
                            {
                                stepIdx = new BaseRemark() { Id = 7, Name = "放款" + Progress_State.已完成, Value = loanEntity.ProvideTime, Remark = loanEntity.ProvideRemark };// 7;
                            }
                            else if (loanEntity.ProvideState == 3)
                            {
                                stepIdx = new BaseRemark() { Id = 7, Name = "放款" + Progress_State.已终止, Value = loanEntity.ProvideTime, Remark = loanEntity.ProvideRemark };//7;
                            }
                        }

                    }

                }
            }

            return stepIdx;

        }

        private BaseRemark GetTransferProgressState(FinanceRunnings entity, FinanceTransferRunnings loanEntity)
        {

            BaseRemark stepIdx = new BaseRemark();//  0;

            if (entity.FilingState == 1)//报备待审核
            {
                stepIdx = new BaseRemark() { Id = 0, Name = "报备待审核", Value = entity.FilingTime };//0
            }
            else if (entity.FilingState == 3)
            {
                stepIdx = new BaseRemark() { Id = 0, Name = "报备审核" + Progress_State.已终止, Value = entity.FilingAuditingTime, Remark = entity.FilingAuditingRemark };//0;
            }
            else if (entity.FilingState == 2)
            {//报备审核已完成
             //stepIdx = new BaseName() { Id = 0, Name = "报备待审核" };//1;
                if (entity.CollectDataState == 1)//搜集资料待完成
                {
                    stepIdx = new BaseRemark() { Id = 1, Name = "备件" + Progress_State.进行中, Value = entity.FilingAuditingTime, Remark = entity.FilingAuditingRemark };//1;
                }
                else if (entity.CollectDataState == 3)//资料不全，被终止
                {
                    stepIdx = new BaseRemark() { Id = 1, Name = "备件" + Progress_State.已终止, Value = entity.CollectDataTime, Remark = entity.CollectDataRemark };//0;
                }
                else if (entity.CollectDataState == 2)////搜集资料已完成
                {
                    //stepIdx = new BaseRemark() { Id = 2, Name = "资料搜集 已完成", Value = frViewModel.FilingAuditingTime, Remark = entity.CollectDataRemark };//2;
                    if (loanEntity.QueryArchivesState == 0)//分配办件人
                    {
                        stepIdx = new BaseRemark() { Id = 2, Name = "备件" + Progress_State.已完成, Remark = entity.CollectDataRemark };//2;
                        if (entity.TransactStaffID != 0)
                        {
                            stepIdx = new BaseRemark() { Id = 3, Name = "面签准备中", Remark = loanEntity.QueryArchivesRemark };//3;
                        }
                    }
                    else if (loanEntity.QueryArchivesState == 1)
                    {
                        stepIdx = new BaseRemark() { Id = 4, Name = "查档" + Progress_State.进行中, Value = loanEntity.QueryArchivesTime, Remark = loanEntity.QueryArchivesRemark };//4;
                    }
                    else if (loanEntity.QueryArchivesState == 3)
                    {
                        stepIdx = new BaseRemark() { Id = 4, Name = "查档" + Progress_State.已终止, Value = loanEntity.QueryArchivesTime, Remark = loanEntity.QueryArchivesRemark };//4;
                    }
                    else if (loanEntity.QueryArchivesState == 2)
                    {
                        //stepIdx = new BaseRemark() { Id = 5, Name = "过户 进行中", Value = frViewModel.ContractTime, Remark = loanEntity.QueryArchivesRemark };//5;
                        if (loanEntity.TransferState == 1)//审批进行中
                        {
                            stepIdx = new BaseRemark() { Id = 5, Name = "过户" + Progress_State.已完成, Remark = loanEntity.TransferRemark };//5;
                        }
                        else if (loanEntity.TransferState == 3)
                        {
                            stepIdx = new BaseRemark() { Id = 5, Name = "过户" + Progress_State.已终止, Value = loanEntity.TransferTime, Remark = loanEntity.TransferRemark };//5;
                        }
                        else if (loanEntity.TransferState == 2)
                        {
                            //stepIdx = new BaseRemark() { Id = 6, Name = "过户 已完成", Value = frViewModel.ApproveTime, Remark = loanEntity.TransferRemark };//6;
                            if (loanEntity.CredentialsState == 1)
                            {
                                stepIdx = new BaseRemark() { Id = 6, Name = "下证" + Progress_State.进行中, Value = loanEntity.CredentialsTime, Remark = loanEntity.CredentialsRemark };//6;
                            }
                            else if (loanEntity.CredentialsState == 2)
                            {
                                stepIdx = new BaseRemark() { Id = 7, Name = "下证" + Progress_State.已完成, Value = loanEntity.CredentialsTime, Remark = loanEntity.CredentialsRemark };// 7;
                            }
                            else if (loanEntity.CredentialsState == 3)
                            {
                                stepIdx = new BaseRemark() { Id = 7, Name = "下证" + Progress_State.已终止, Value = loanEntity.CredentialsTime, Remark = loanEntity.CredentialsRemark };//7;
                            }
                        }
                    }
                }
            }

            return stepIdx;

        }

    }
}